require 'dm-core'
require 'appengine-apis/users'
require 'appengine-apis/logger'
require 'json'
require 'cgi'



root = File.dirname(__FILE__)
Kernel.load(root+'/tests/tests.rb')

Dir[root+'/util/*.rb'].each { |page|
    Kernel.load(page)
  }

Dir[root+'/pages/*.rb'].each { |page|
    Kernel.load(page)
  }




class App  

  def initialize
    DataMapper.setup(:default, "appengine://auto")
  end

  def run env
    request = Rack::Request.new(env)

    if e = request.params['event']
      return event(JSON.parse(e)).to_json
    else
      ev_name = 'url:'+((env["PATH_INFO"] || '/').split('/')[1] || '')
      response = Event.fire(ev_name, {
          :env => env,
          :request => request
        }).first
      if response
        response.html
      else
        raise "No response for #{ev_name}."
      end
    end
  end

  def event e
    Event.fire(e['name'], e)
  end

	def self.run env    
    once.each { |b| b.call }
    (@@instance ||= new).run env
	end



end
